package com.jdwx.opengl.kotlin

import kotlinx.coroutines.*


suspend fun failedConcurrentSum(): Int = coroutineScope {
    val one = async<Int> {
        try {
            delay(5000L) // 模拟一个长时间的运算
            42
        } finally {
            println("First child was cancelled")
        }
    }
    val two = async<Int> {
        println("Second child throws an exception")
        throw ArithmeticException()
        20
    }
    one.await() + two.await()
}

//fun main() = runBlocking<Unit> {
//    try {
//        var sum  = failedConcurrentSum()
//        print( sum )
//    } catch(e: ArithmeticException) {
//        println("Computation failed with ArithmeticException")
//    }

    //调度器
//    launch { // 运行在父协程的上下文中，即 runBlocking 主协程
//        println("1main runBlocking      : I'm working in thread ${Thread.currentThread().name}")
//    }
//    launch(Dispatchers.Unconfined) { // 不受限的——将工作在主线程中
//        println("2Unconfined            : I'm working in thread ${Thread.currentThread().name}")
//    }
//    launch(Dispatchers.Default) { // 将会获取默认调度器
//        println("3Default               : I'm working in thread ${Thread.currentThread().name}")
//    }
//    launch(newSingleThreadContext("MyOwnThread")) { // 将使它获得一个新的线程
//        println("4newSingleThreadContext: I'm working in thread ${Thread.currentThread().name}")
//    }

//    launch(Dispatchers.Unconfined) { // 非受限的——将和主线程一起工作
//        println("Unconfined      : I'm working in thread ${Thread.currentThread().name}")
//        delay(1000)
//        println("Unconfined      : After delay in thread ${Thread.currentThread().name}")
//    }
//    launch { // 父协程的上下文，主 runBlocking 协程
//        println("main runBlocking: I'm working in thread ${Thread.currentThread().name}")
//        delay(1000)
//        println("main runBlocking: After delay in thread ${Thread.currentThread().name}")
//    }
//
//}

//调试协程与线程
//fun log(msg: String) = println("[${Thread.currentThread().name}] $msg")
//
//fun main() = runBlocking<Unit> {
//    val a = async {
//        log("I'm computing a piece of the answer")
//        6
//    }
//    val b = async {
//        log("I'm computing another piece of the answer")
//        7
//    }
//    log("The answer is ${a.await() * b.await()}")
//}
//
//fun main(){
//    newSingleThreadContext("Ctx1").use { ctx1 ->
//
//        newSingleThreadContext("Ctx2").use { ctx2 ->
//            runBlocking(ctx1) {
//                log("Started in ctx1")
//                withContext(ctx2) {
//                    log("Working in ctx2")
//                }
//
//                log("Back to ctx1")
//            }
//        }
//
//    }
//}


//fun main() = runBlocking {
//
//    // 启动一个协程来处理某种传入请求（request）
//    val request = launch {
//        repeat(3) { i -> // 启动少量的子作业
//            launch  {
//                delay((i + 1) * 200L) // 延迟 200 毫秒、400 毫秒、600 毫秒的时间
//                println("Coroutine $i is done")
//            }
//        }
//        println("request: I'm done and I don't explicitly join my children that are still active")
//    }
//    request.join() // 等待请求的完成，包括其所有子协程
//    println("Now processing of the request is complete")
//
//}
fun log(msg: String) = println("[${Thread.currentThread().name}] $msg")
fun main() = runBlocking (CoroutineName("main")){

//    log("Started main coroutine")
//// 运行两个后台值计算
//    val v1 = async(CoroutineName("v1coroutine")) {
//        delay(500)
//        log("Computing v1")
//        252
//    }
//    val v2 = async(CoroutineName("v2coroutine")) {
//        delay(1000)
//        log("Computing v2")
//        6
//    }
//    log("The answer for v1 / v2 = ${v1.await() / v2.await()}")
//    var a = launch(Dispatchers.Default + CoroutineName("test")) {
//        println("I'm working in thread ${Thread.currentThread().name}")
//    }
//    a.join()
//
//    val mainScope = MainScope()
//    mainScope.cancel()
//
//    open class A{
//        constructor(name:Int){
//
//        }
//    }

    class Activity : CoroutineScope by CoroutineScope(Dispatchers.Default) {

        fun destroy() {
            cancel() // Extension on CoroutineScope
        }
        // 继续运行……

        // class Activity continues
        fun doSomething() {
            // 在示例中启动了 10 个协程，且每个都工作了不同的时长
            repeat(10) { i ->
                launch {
                    delay((i + 1) * 200L) // 延迟 200 毫秒、400 毫秒、600 毫秒等等不同的时间
                    println("Coroutine $i is done")
                }
            }
            runBlocking {

            }
            GlobalScope.launch {  }
        }
    } // Activity 类结束
    val activity = Activity()
    activity.doSomething() // 运行测试函数
    println("Launched coroutines")
    delay(500L) // 延迟半秒钟
    println("Destroying activity!")
    activity.destroy() // 取消所有的协程
    delay(1000) // 为了在视觉上确认它们没有工作
    runBlocking {
        var a = launch {  }
    }
}





